package com.flyduck.annotation.interceptor;

import com.flyduck.annotation.annotation.HeaderValidInterceptor;
import com.flyduck.annotation.util.CommonUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器处理注解逻辑
 *
 * @author flyduck 2020/10/22 21:40
 * @version V1.0
 * @modify by user: flyduck 2020/10/22
 * @modify by reason:{原因}
 **/
@Component
public class HeaderInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 判断handler是否为方法声明类型
        if (handler instanceof HandlerMethod) {
            // 获取自定义注解
            HeaderValidInterceptor headerValid = ((HandlerMethod) handler).getMethodAnnotation(HeaderValidInterceptor.class);
            if (headerValid != null) {
                // 判断自定义注解验证逻辑
                String allowRole = headerValid.value();
                String requestRole = request.getHeader(CommonUtils.HEADER_CLIENT);
                if (!allowRole.equals(requestRole)) {
                    return false;
                }
            }
        }

        return super.preHandle(request, response, handler);
    }
}
